﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LKVMLMApp.StaticClass;
using System.ComponentModel;
using LKVMLMLib;
using LKVMLMADMIN.Models;
using System.IO;
using PagedList;
using LKVMLMADMIN.Extension;
using System.Globalization;
using PinService.Lib;
using PinService;
using LKVMLMADMIN.Common;

namespace LKVMLMADMIN.Controllers
{
    public class CongCuController : Controller
    {
        public class Choose
        {
            public string ProfitName { get; set; }
            public double? Amount { get; set; }
        }
        public class Tinhtoan
        {
            public int ID { get; set; }
            public string CommissionName { get; set; }
            public string Description { get; set; }
            public string Status { get; set; }
            public string Action { get; set; }
        }
        // GET: /CongCu/
        public LKVService.ProfitService Profitservice = new LKVService.ProfitService();
        public LKVService.User userService = new LKVService.User();
        public ActionResult SaleManager(string Fromdate = "", string Todate = "")
        {
            if (Session["User"] != null)
            {             
                DateTime FromDate1;
                DateTime ToDate1;
                if (Fromdate == "")
                    FromDate1 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                else
                    FromDate1 = Convert.ToDateTime(Fromdate);
                if (Todate == "")
                    ToDate1 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1);
                else
                    ToDate1 = Convert.ToDateTime(Todate);
                var ListHoaHong = Profitservice.getListProfit(FromDate1, ToDate1);
                var listTenHoaHong = Profitservice.getListCommissionConfig(true, false);
                var temptQ = from nc in listTenHoaHong.ToList()
                             join c in ListHoaHong.ToList() on nc.CommissionName equals c.ProfitType
                                 into ls
                             from c in ls.DefaultIfEmpty()
                             select new { CommissionName = nc.CommissionName, CommissionDesc = nc.CommissionDesc, Amount = (c == null) ? 0 : c.Amount };
                var ListCommission = from l in temptQ group l by l.CommissionName into c select new Choose { ProfitName = c.FirstOrDefault().CommissionDesc, Amount = c.Sum(s => s.Amount) };
                ViewBag.DanhSach = ListCommission.ToList();
                double a = Profitservice.SumOder(FromDate1, ToDate1);
                ViewBag.Tongdauvao = a;
                double b = Profitservice.SumProfit(FromDate1, ToDate1);
                double r = a - b;
                ViewBag.Daura = b;
                ViewBag.Loinhuan = r;
                return View();
            }
            else
                return RedirectToAction("Login", "Account");
        }
        public ActionResult ResetData()
        {
            if (Session["User"] != null)
            {
                var extenssion = new LKVService.User();            
                extenssion.ResetData();
                return View();
            }
            else
                return RedirectToAction("Login", "Account");
        }
        [AllowAnonymous]
        public ActionResult TinhToanHoaHong(int month = 0, int selectedyear = 0)
        {         
            var db = new LKVService.ProfitService();
            if (month == 0)
                month = DateTime.Now.Month;
            ViewBag.Month = month;
            if (selectedyear == 0)
                selectedyear = DateTime.Now.Year;
            ViewBag.Selectedyear = Convert.ToInt32(selectedyear);
            List<string> yd = new List<string>();
            for (int y = 2013; y <= DateTime.Now.Year; y++)
                yd.Add(y.ToString());
            ViewBag.Year = yd;
            var ListDSTinh = new List<Tinhtoan>();
            if (month > 0 && selectedyear > 0)
            {
                var _lsCommis = db.getListCommissionConfig(false, true);
                var _lsCommisYear = db.FindCommissionMonthYear(month, selectedyear).ToList();
                if (_lsCommisYear.Count == 0)
                {
                    ListDSTinh = _lsCommis.Select(x => new Tinhtoan
                    {
                        ID = 0,
                        CommissionName = x.CommissionName,
                        Description = x.CommissionDesc,
                        Status = "Chưa tính",
                        Action = "Tính hoa hồng"
                    }).ToList();
                }
                else
                {
                    ListDSTinh = _lsCommis.LeftJoin(_lsCommisYear,
                            p => p.CommissionName,
                            c => c.CommissionName,
                            (p, c) => new { com = p, comer = c }
                        ).Select(x => new Tinhtoan
                        {
                            ID = x.comer != null ? x.comer.ID : 0,
                            CommissionName = x.com.CommissionName,
                            Description = x.com.CommissionDesc,
                            Status = x.comer != null ? "Đã tính" : "Chưa tính",
                            Action = "Tính hoa hồng"
                        }).ToList();

                }
            }
            ViewBag.TinhToan = ListDSTinh;
            return View();
        }
        [HttpPost]
        [AllowAnonymous]
        public ActionResult TinhToanHoaHong(int month = 0, int selectedyear = 0, int b =0)
        {        
            if (month == 0)
                month = DateTime.Now.Month;
            ViewBag.Month = month;
            if (selectedyear == 0)
                selectedyear = DateTime.Now.Year;
            ViewBag.Selectedyear = Convert.ToInt32(selectedyear);
            List<string> yd = new List<string>();
            for (int y = 2013; y <= DateTime.Now.Year; y++)
                yd.Add(y.ToString());
            ViewBag.Year = yd;
            var db = new LKVService.ProfitService();
            var ListDSTinh = new List<Tinhtoan>();
            if (month > 0 && selectedyear > 0)
            {
                var _lsCommis = db.getListCommissionConfig(false, true);
                var _lsCommisYear = db.FindCommissionMonthYear(month, selectedyear).ToList();
                if (_lsCommisYear.Count == 0)
                {
                    ListDSTinh = _lsCommis.Select(x => new Tinhtoan
                    {
                        ID = 0,
                        CommissionName = x.CommissionName,
                        Description = x.CommissionDesc,
                        Status = "Chưa tính",
                        Action = "Tính hoa hồng"
                    }).ToList();
                }
                else
                {
                    ListDSTinh = _lsCommis.LeftJoin(_lsCommisYear,
                            p => p.CommissionName,
                            c => c.CommissionName,
                            (p, c) => new { com = p, comer = c }
                        ).Select(x => new Tinhtoan
                        {
                            ID = x.comer != null ? x.comer.ID : 0,
                            CommissionName = x.com.CommissionName,
                            Description = x.com.CommissionDesc,
                            Status = x.comer != null ? "Đã tính" : "Chưa tính",
                            Action = "Tính hoa hồng"
                        }).ToList();

                }
                ViewBag.TinhToan = ListDSTinh;
                bool check = false;
                foreach (var a in ListDSTinh)
                {
                    string _status = a.Status;
                    if (_status.ToLower() == "true")
                    {
                        check = true;
                        break;
                    }
                }
                if (check == false)
                {
                    db.ExeCuteMonthCommission(month, selectedyear);
                }
               
            }
            return RedirectToAction("TinhToanHoaHong", "CongCu");
        }
        [AllowAnonymous]
        public ActionResult CauHinhHoaHong()
        {        
            var ListCommission =Profitservice.getListCommissionConfig(false, false);
            ViewBag.List = ListCommission;
            return View();
        }
        [HttpPost]
        [AllowAnonymous]
        public ActionResult CauHinhHoaHong(string Check = "", string CommissionName="")
        {         
            var ListCommission = Profitservice.getListCommissionConfig(false, false);
            ViewBag.List = ListCommission;           
            return View();
        }
        [AllowAnonymous]
        public ActionResult WebSite(string error = "")
        {
            if (Session["User"] != null)
            {
               
                return View();
            }
            else
                return RedirectToAction("Login", "Account");
        }
        [HttpPost]
        public ActionResult WebSite(WebsiteModel wm)
        {
            var db = new LKVService.SystemService();
            try 
            { 
                
                return RedirectToAction("WebSite", "CongCu", new { error = "Cập nhật thành công" });
            }
            catch (Exception ex)
            {
                return RedirectToAction("WebSite", "CongCu", new { error = "Cập nhật không thành công" });
            }
        }
        public List<Colors> getThemes()
        {
            var colors = new List<Colors>();
            colors.Add(new Colors{Value = "Gray",Text = "Gray"});
            colors.Add(new Colors { Value = "Black", Text = "Black" });
            colors.Add(new Colors { Value = "Green", Text = "Green" });
            colors.Add(new Colors { Value = "Organge", Text = "Organge" });
            colors.Add(new Colors { Value = "Blue", Text = "Blue" });
            return colors;
        }
        public ActionResult ChangeSatusCommission(string commission, string val)
        {
            var Commission = Profitservice.getListCommissionConfig(false, false).Where(w => w.CommissionName == commission).SingleOrDefault();
            Commission.Status = Convert.ToBoolean(val);
            Profitservice.UpdateCommission(Commission);
            return RedirectToAction("CauHinhHoaHong", "CongCu");
        }
        public ActionResult ConfigTree()
        {
            if (Session["User"] != null)
            {
                var extenssion = new LKVService.User();
                var configParent = extenssion.getConfigTree();
                if (configParent.Option_1 == true)
                {
                    ViewBag.SysTree = "1";
                }
                if (configParent.Option_2 == true)
                {
                    ViewBag.BinaryTree = "2";
                }
                bool System = false;
                bool Binary = false;
                Config _cf = userService.getConfigTree();
                if (_cf != null)
                {
                    if (_cf.Option_1 == true)
                    {
                        System = true;
                    }
                    if (_cf.Option_2 == true)
                    {
                        Binary = true;
                    }
                }
                ViewBag.HT = System;
                ViewBag.NP = Binary;
                return View();
            }
            else
                return RedirectToAction("Login", "Account");
        }
        public ActionResult Backup(string Name)
        {
            return View();
        }
        public ActionResult ChangeSatusTree(string _id, string val)
        {
            int a = Convert.ToInt32(_id);
            Config _cfE = userService.getConfigTree();   
            if(a==1)      
            _cfE.Option_1 = Convert.ToBoolean(val);
            if(a==2)
            _cfE.Option_2 = Convert.ToBoolean(val);  
            userService.UpdateConFig(_cfE);
            return RedirectToAction("ConfigTree", "CongCu");
        }
        [HttpPost]
        public ActionResult UploadFile()
        {
            var file = Request["qqfile"];
            string fileName = "";
            string _domain = string.Empty;
            string folder = string.Empty;
            string url = Request.Url.GetLeftPart(UriPartial.Authority);
            bool checkLocal = true;
            if (!url.Contains("localhost"))
            {
                checkLocal = false;
            }
            //string vituarl = string.Empty; 
            if (checkLocal == false)
            {
                if (url.Contains("http://"))
                {
                    url = url.Substring(7, url.Length - 7);
                    string[] arrDomain = url.Split('.');
                    for(int i= 1;i<arrDomain.Count();i++)
                    { 
                        _domain += arrDomain[i].ToString();
                        //if (i != 1 && i != arrDomain.Count())
                        //{
                        //    _domain = _domain + ".";
                        //}
                    }
                    folder = Server.MapPath("~/Images/" + _domain + "/"); 
                }
                else if (url.Contains("https://"))
                {
                    url = url.Substring(8, url.Length - 8);
                    string[] arrDomain = url.Split('.');
                    for (int i = 1; i < arrDomain.Count(); i++)
                    {
                        _domain += arrDomain[i].ToString();                      
                    }
                    folder = Server.MapPath("~/Images/" + _domain + "/"); 
                }
            }else
            {
                folder = Server.MapPath("~/Images/");
            }
            try
            {
                var stream = Request.InputStream;
                if (String.IsNullOrEmpty(file))
                {
                    // IE
                    HttpPostedFileBase postedFile = Request.Files[0];
                    stream = postedFile.InputStream;

                    fileName = Path.GetFileName(Request.Files[0].FileName);
                }
                else
                {
                    //Webkit, Mozilla
                    fileName = file;
                }

                if (this.CreateFolderIfNeeded(folder))
                {
                    var buffer = new byte[stream.Length];
                    stream.Read(buffer, 0, buffer.Length);
                    System.IO.File.WriteAllBytes(folder + fileName, buffer);
                }
                string currentLink = string.Empty;
                if (checkLocal == false)
                    currentLink = Request.Url.GetLeftPart(UriPartial.Authority) + "/Images/" + _domain + "/" + fileName;
                else
                    currentLink = "../Images/"+ fileName;

                return Json(new { success = true, status = "success", message = "LBL_SuccessImage", link = currentLink }, "text/html");
            }
            catch (Exception exs)
            {
                return Json(new { success = false, status = "Error", message = exs }, "text/html");
            }
            
        }
        private bool CreateFolderIfNeeded(string path)
        {
            bool result = true;
            if (!Directory.Exists(path))
            {
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch (Exception)
                {
                    result = false;
                }
            }
            return result;
        }
        public ActionResult CashOut(int page = 1, int _Status = 0,string _error = "")
        {
            if (Session["User"] != null)
            {
                return View();
            }
            else
                return RedirectToAction("Login", "Account");

        }
        public ActionResult ApprovePM(int _wdId = 0, int _status = 0, int _method = 0, int _userId = 0, double _amount = 0)
        {
            var helper = new StringHelper();
            var code = StringHelper.RandomString(5) + helper.MD5Hash(DateTime.Now.ToString());
            var ts = new LKVService.Transaction();
            var kq = ts.updateStatusWithdrawAndCode(_wdId, 1, code);
            if (kq == true)
                return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Thành công" });
            else
                return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Thất bại" });
            //var val = this.ApprovePMFunction(_wdId ,  _status  ,  _method  ,  _userId  ,  _amount  );
            //switch (val)
            //{
            //    case "-1":
            //        return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Chưa cấu hình tài khoản gốc" });
            //    case "-2":
            //        return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Chưa cấu hình tài khoản gốc" });
            //    case "-3":
            //        return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Không tìm thấy tài khoản Pefect Money nhận" });
            //    case "-4":
            //        return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "ERROR" });
            //    case "-5":
            //        return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Không thành công" });
            //    case "1":
            //        return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Thành công" }); 
            //    case "-12":
            //        return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Chưa hổ trợ công thanh toán" });                                                                  
            //    case "-6":
            //        return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Lệnh rút không tồn tai" });
            //    case "-7":
            //        return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Không xác định được kiểu thanh toán" });
            //    case "-8":
            //        return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Trạng thái Pending mới cho phép Approve" });
            //    case "-9":
            //        return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Không xác định được tài khoản nhận" });
            //    case "-10":
            //        return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Số tiền phải lớn hơn 0" });
            //    case "-11" :
            //        return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Lỗi chưa xác định" });
            //    default:
            //        return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = val });
            //}
            
        }
        public ActionResult CancelPM(int _wdId = 0, int _status = 0, int _userId = 0, double _amount = 0, int _walletId = 0)
        {
            if (_wdId != 0 && _status == 0 && _userId != 0 && _walletId != 0)
             {
                 var ts = new LKVService.Transaction();
                 var returnval = _amount*(1+  ts.getCashoutFee());
                 bool kp = ts.chargeFormWallet(_userId,_walletId,returnval , "Refund money");
                 if(kp == false)
                     return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Không thành công" });
                 bool kq = ts.updateStatusWithdraw(_wdId, 2);
                 if (kq == false)
                     return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Không thành công" });                
             }else
             {
                 if (_wdId == 0)
                     return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Lệnh rút không tồn tai" });
                 if (_status != 0)
                     return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Trạng thái Pending mới cho phép Approve" });
                 if (_userId == 0)
                     return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Không xác định tài khoản trả lại" });
                if(_walletId == 0)
                    return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Không xác định kiểu ví tiền" });
             }
             return RedirectToAction("CashOut", "CongCu", new { _Status = _status, _error = "Thành công" }); 
        }
        public IEnumerable<SelectListItem> createDDLStatus(int _status = 0)
        {
            var _ddl = new List<SelectListItem>();
            _ddl.Add(new SelectListItem()
            { 
                Text = "Pending",
                Value = "0",
                Selected = _status == 1 ? true : false
            });
            _ddl.Add(new SelectListItem()
            {
                Text = "Approve",
                Value = "1",
                Selected = _status == 1 ? true : false
            });
            _ddl.Add(new SelectListItem()
            {
                Text = "Cancel",
                Value = "2",
                Selected = _status == 2 ? true : false
            });
            return _ddl.AsEnumerable(); 
        }
        [AllowAnonymous]
        public ActionResult AddmoneyToUser()
        {
            if (Session["User"] != null)
            {
                var extenssion = new LKVService.User();
                var trans = new LKVService.Transaction();
                ViewBag.list_user = extenssion.getListUser();
                ViewBag.wallets = trans.listWallet();
                return View();
            }
            else
                return RedirectToAction("Login", "Account");
           
        }
        [HttpPost]
        [AllowAnonymous]
        public ActionResult AddmoneyToUser(string suserid, string samount, string swalletid ,string desc)
        {
            if (Session["User"] != null)
            {
                int userid = Convert.ToInt32(suserid);
                double amount = Convert.ToDouble(samount);
                int walletid = Convert.ToInt32(swalletid);
                var extenssion = new LKVService.Transaction();
                extenssion.chargeFormWallet(userid, walletid, amount, desc);
                return RedirectToAction("AddmoneyToUser", "CongCu", new { _Status = 1, _error = "Thành công" });
            }
            else
                return RedirectToAction("Login", "Account");
        }
      
        [AllowAnonymous]
        public ActionResult AddFundManager(int page = 1, int user = 0, int PRMT = 0,DateTime? Fromdate = null,DateTime? Todate = null, int check =0)
        {
            if (Session["User"] != null)
            {
                var extenssion = new LKVService.Transaction();
                var _ListParentMethod = extenssion.GetPaymentMethods().Select(s => new LKVMLMADMIN.Models.loadPaymentMethodModels { id = s.Id, Name = s.Name }).ToList();
                _ListParentMethod.Insert(0, new LKVMLMADMIN.Models.loadPaymentMethodModels { id = 0, Name = "Select " });
                ViewBag.ParentMT = _ListParentMethod;
                var Listuser = userService.getListUser();
                var ListUsername = Listuser.Select(x => new LKVMLMADMIN.Models.loadCommissionModels { userid = x.UserId, UserName = x.UserName }).ToList();
                ListUsername.Insert(0, new LKVMLMADMIN.Models.loadCommissionModels { userid = 0, UserName = "Select User" });
                ViewBag.Username = ListUsername;
                if (user != 0)
                    Session["uid"] = user.ToString();
                int uids = 0;
                if(check ==1)
                uids =Convert.ToInt32( Session["uid"]);
                if (check == 0 && user == 0)
                {
                    uids = user;
                    Session["uid"] = null;
                }
                
                DateTime From;
                DateTime To;
                if (Fromdate == null)
                    From = DateTime.Now.AddDays(-30).Date;
                else            
                        From = Convert.ToDateTime(Fromdate);
               
             
                if (Todate == null)
                    To = DateTime.Now.Date;
                else            
                        To = Convert.ToDateTime(Todate);             
                ViewBag.DateFrom = From;
                ViewBag.Todate = To;
                var _ListShow = extenssion.getLisAddFundWithCondition(user, PRMT, From, To, (page - 1) * 100, 100);
                var ListAddFund = _ListShow.Item2;             
                int[] myArray = Enumerable.Repeat(-1, _ListShow.Item1).ToArray();
                ViewBag.Showlist = ListAddFund;
                return View(myArray.ToPagedList(page, 100));
            }
            else
                return RedirectToAction("Login", "Account");

        }
        [AllowAnonymous]
        public ActionResult PinManager(string msg = "") 
        {
            if (Session["User"] != null)
            {
                var extenssion = new LKVService.User();
                ViewBag.list_user = extenssion.getListUser();
                ViewBag.msg = msg;
                return View();
            }
            else
                return RedirectToAction("Login", "Account");
        }
        [AllowAnonymous]
        [HttpPost]
        public ActionResult PinManager(string suserid, string sQuantum)
        {
            if (Session["User"] != null)
            {
                int userid = Convert.ToInt32(suserid);
                int quantum = Convert.ToInt32(sQuantum);
                var db = new LKVService.User();
                var user = db.findUserById(userid);
                var userlogin = Session["User"] as LKVMLMLib.UserProfile;
                var extenssion = new MaThePaymentService();
                if (quantum > 0)
                {
                    for (int i = 0; i < quantum;i++ )
                    {
                        extenssion.AddPin(new PinService.MaThe
                        {
                            Amount = 1,
                            CreateDate = DateTime.Now,
                            Series = extenssion.generateMaThe(),
                            Used = false,
                            UserId = userid
                        }                        
                       );
                    }
                    extenssion.addPinHistory(userlogin.UserId, userid, quantum);

                    return RedirectToAction("PinManager", "CongCu", new { msg = "" + quantum + " đã được thêm thành công cho " + user.UserName + "" });
                }
                return RedirectToAction("PinManager", "CongCu", new { msg = "Thất bại" });
            }
            else
                return RedirectToAction("Login", "Account");
        }
        public ActionResult DanhSachPin(int page = 1, string Fromdate = "", string Todate = "")
        {

            if (Session["User"] != null)
            {
                MaThePaymentService pinService = new MaThePaymentService();
                DateTime fromdate;
                DateTime todate;
                if (Fromdate == "")
                    fromdate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                else
                {
                    fromdate = Convert.ToDateTime(Fromdate);
                    ViewBag.DateFrom = Fromdate;
                }
                if (Todate == "")
                    todate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1);
                else
                {
                    todate = Convert.ToDateTime(Todate);
                    ViewBag.Todate = Todate;
                }
                var Tonghop = pinService.getPinActiveOnDay(fromdate.Date, todate.Date, (page - 1) * 50, 50);
                var ListPin = Tonghop.Item2;
                double? Sumamount = 0;
                if (ListPin != null)
                    Sumamount = ListPin.Sum(s => s.Amount);
                ViewBag.tongtien = Sumamount;
                int[] myArray = Enumerable.Repeat(-1, Tonghop.Item1).ToArray();
                ViewBag.DoanhSo = ListPin;
                return View(myArray.ToPagedList(page, 50));
            }
            else
                return RedirectToAction("Login", "Account");
        }
    }
}
